package com.wwwarehouse.contract.contract;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.contract.bean.SettingRuleBean;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.customview.AutoClickButton;
import com.wwwarehouse.contract.event.RefreshEvent;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

import static contract.wwwarehouse.com.contract.R.id.price;

/**
 * @author Joseph on 2017/10/24.
 *         <p/>
 *         添加发布规则
 */

public class ReleaseAddingPublishingRulesFragment extends TheParentFragment implements View.OnClickListener {

    private TextView mTvPrice;
    private AppCompatButton mTypeFixed; //固定价格
    private AppCompatButton mTypeProportion; //参考比例
    private TextInputLayout mTilPrice;
    private TextInputLayout mTilQty;
    private EditText mEdtePrice;
    private TextView mTvQty;
    private AppCompatButton mQtyTypeTixed;  // 固定数量
    private AppCompatButton mQtyTypeProportion; //按库存数比例发布
    private EditText mEdtQty;
    private TextView mPricePro;
    private TextView mQtyPro;
    private AutoClickButton mBtnConfirm;
    private SettingRuleBean.DataBean.ListBean data;
    private int position;
    private int pos;
    private String pbUkid;
    private LinearLayout mLLPrice;
    private LinearLayout mLLPb;
    private String mPriceProValue;
    private String mPriceValue;
    private String mQtyCount;
    private String mQtyCountPro;
    private String mPriceGuding;
    private String mPriceBili;
    private String mQtyGuding;
    private String mQtyBili;

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ReleaseAddingPublishingRulesFragment) {
            mActivity.setTitle("添加发布规则");
        }
    }

    @Override
    protected int getContentId() {
        return R.layout.adding_publishing_rules;
    }

    private String priceRuleType;
    private String qtyRuleType;

    @Override
    protected void init(View view) {
        Bundle bundle = getArguments();
        if (bundle != null) {
            data = (SettingRuleBean.DataBean.ListBean) bundle.getSerializable("data");
            position = bundle.getInt("position");
            pos = bundle.getInt("pos");
            pbUkid = bundle.getString("pbUkid");
        }
        mPricePro = findView(view, R.id.price_proportion);
        mQtyPro = findView(view, R.id.qty_proportion);
        mTvPrice = findView(view, price);
        mTypeFixed = findView(view, R.id.price_type_fixed);
        mTypeProportion = findView(view, R.id.price_type_proportion);
        mTilPrice = findView(view, R.id.til_price);
        mEdtePrice = findView(view, R.id.edt_price);
        mTvQty = findView(view, R.id.qty);
        mQtyTypeTixed = findView(view, R.id.qty_type_fixed);
        mQtyTypeProportion = findView(view, R.id.qty_type_proportion);
        mTilQty = findView(view, R.id.til_qty);
        mEdtQty = findView(view, R.id.edt_qty);
        mBtnConfirm = findView(view, R.id.confirm_btn);
        mLLPrice = findView(view, R.id.ll_price);
        mLLPb = findView(view, R.id.ll_pb);

        mTilPrice.setVisibility(View.GONE);
        mTilQty.setVisibility(View.GONE);

        mLLPrice.setVisibility(View.GONE);
        mLLPb.setVisibility(View.GONE);
        mBtnConfirm.bindEditText(mEdtePrice);
        mBtnConfirm.bindEditText(mEdtQty);
        setRule();

    }

    private void setRule() {
        if (data.getPrice() != 0) {
            mTvPrice.setText("(参考价格:" + data.getPrice() + "元)");
        } else {
            mTilPrice.setVisibility(View.VISIBLE);
            mTvPrice.setText("(参考价格:---)");
            priceRuleType = "0";
            mTypeFixed.setSelected(true);
            mTypeProportion.setEnabled(false);
            mTypeProportion.setTextColor(Color.parseColor("#d5d7dc"));
            mEdtePrice.setHint("输入固定的发布价格（单位：元）");
            mTilPrice.updateHint();
            setPriceHint();
        }
        if (data.getQty() != null) {
            if (data.getUnit() != null)
                mTvQty.setText("(库存:" + data.getQty() + data.getUnit() + ")");
            else
                mTvQty.setText("(库存:" + data.getQty() + ")");

        } else {
            mTilQty.setVisibility(View.VISIBLE);
            qtyRuleType = "0";
            mQtyTypeTixed.setSelected(true);
            mQtyTypeProportion.setEnabled(false);
            mQtyTypeProportion.setTextColor(Color.parseColor("#d5d7dc"));
            if (data.getUnit() != null)
                mTvQty.setText("(库存:" + "0" + data.getUnit() + ")");
            else
                mTvQty.setText("(库存:0)");
            mEdtQty.setHint("输入固定的发布数量（单位：" + data.getUnit() + "）");
            mTilQty.updateHint();
            setQtyHint();

        }
        //数量规则类型（0、固定数量 1、库存比例）
        if (data.getQtyRuleType() != null) {
            if (data.getQty() != null) {
                mQtyTypeTixed.setEnabled(true);
                mQtyTypeProportion.setEnabled(true);
            } else {
                mQtyTypeTixed.setSelected(true);
                mQtyTypeProportion.setEnabled(false);
                mQtyTypeProportion.setTextColor(Color.parseColor("#d5d7dc"));
            }
            mTilQty.setVisibility(View.VISIBLE);
            qtyRuleType = data.getQtyRuleType();
            if ("0".equals(data.getQtyRuleType())) {
                setQtyHint();
                mQtyTypeTixed.setSelected(true);
                mQtyTypeProportion.setSelected(false);
                mEdtQty.setText(data.getQtyRuleValue());
                mEdtQty.setHint("固定的发布数量（单位：" + data.getUnit() + "）");
                mQtyGuding = data.getQtyRuleValue();
                mQtyBili = null;
                mTilQty.updateHint();

            } else if ("1".equals(data.getQtyRuleType())) {
                setQtyPro();
                mQtyTypeTixed.setSelected(false);
                mQtyTypeProportion.setSelected(true);
                mEdtQty.setText(data.getQtyRuleValue());
                mQtyGuding = null;
                mQtyBili = data.getQtyRuleValue();
                mEdtQty.setInputType(8194);
                mEdtQty.setHint("比例 (可大于100) %");
                mTilQty.updateHint();

            }
        }
        //        价格规则类型（0、固定价格 1、参考价比例）
        if (data.getPriceRuleType() != null) {
            if (data.getPrice() != 0) {
                mTypeFixed.setEnabled(true);
                mTypeProportion.setEnabled(true);
            } else {
                mTypeFixed.setSelected(true);
                mTypeProportion.setEnabled(false);
                mTypeProportion.setTextColor(Color.parseColor("#d5d7dc"));
            }
            mTilPrice.setVisibility(View.VISIBLE);
            priceRuleType = data.getPriceRuleType();
            if ("0".equals(data.getPriceRuleType())) {
                setPriceHint();
                mTypeFixed.setSelected(true);
                mTypeProportion.setSelected(false);
                mEdtePrice.setText(data.getPriceRuleValue());
                mEdtePrice.setHint("固定的发布价格（单位：元）");
                mTilPrice.updateHint();
            } else if ("1".equals(data.getPriceRuleType())) {
                setPricePro();
                mTypeFixed.setSelected(false);
                mTypeProportion.setSelected(true);
                mEdtePrice.setText(data.getPriceRuleValue());
                mEdtePrice.setHint("比例 (可大于100) %");
                mTilPrice.updateHint();
            }
        }
    }


    @Override
    protected void loadDatas() {
        mBtnConfirm.setOnClickListener(this);
        mTypeFixed.setOnClickListener(this);
        mQtyTypeTixed.setOnClickListener(this);
        mTypeProportion.setOnClickListener(this);
        mQtyTypeProportion.setOnClickListener(this);
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        if (what == 0) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                SettingRuleBean.DataBean.ListBean bean = new SettingRuleBean.DataBean.ListBean();
                bean.setHasSetRule(true);
                bean.setItemTempUkid(data.getItemTempUkid());
                bean.setPriceRuleType(priceRuleType);
                bean.setPriceRuleValue(Double.parseDouble(mEdtePrice.getText().toString().trim()) + "");
                bean.setQtyRuleType(qtyRuleType);
                bean.setQtyRuleValue(mEdtQty.getText().toString().trim());
                bean.setPrice(data.getPrice());
                bean.setQty(data.getQty());
                bean.setUnit(data.getUnit());
                bean.setBarCode(data.getBarCode());
                bean.setCreateTime(data.getCreateTime());
                bean.setCreateUserId(data.getCreateUserId());
                bean.setCreateTime(data.getCreateTime());
                bean.setDefinedUkid(data.getDefinedUkid());
                bean.setImg(data.getImg());
                bean.setMarque(data.getMarque());
                bean.setName(data.getName());
                bean.setPbUkid(data.getPbUkid());
                EventBus.getDefault().post(new RefreshEvent(position, pos, bean));
                popFragment();
            } else {
                toast(commonClass.getMsg());
            }
        }
    }

    @Override
    public void onReLoad(int code) {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.confirm_btn) {
            if (data != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("itemTempUkid", data.getItemTempUkid());
                if (mEdtePrice.getText().toString().startsWith("00")) {
                    toast("价格必须大于零");
                    return;
                }
                if (!mTypeProportion.isSelected()) {
                    map.put("pbPrice", mEdtePrice.getText().toString().trim());
                } else {
                    map.put("pbPrice", mPricePro.getText().toString().trim());
                }
                if (mEdtQty.getText().toString().startsWith("0")) {
                    toast("数量必须大于零");
                    return;
                }
                if (!mQtyTypeProportion.isSelected()) {
                    map.put("pbQty", mEdtQty.getText().toString().trim());
                } else {
                    map.put("pbQty", mQtyPro.getText().toString().trim());
                }
                map.put("pbQtyUnit", data.getPbQtyUnit());
                map.put("pbQtyUnitUkid", data.getPbQtyUnitUkid());
                map.put("pbUkid", pbUkid);
                map.put("priceRuleType", priceRuleType);
                map.put("priceRuleValue", mEdtePrice.getText().toString().trim());
                map.put("qtyRuleType", qtyRuleType);
                map.put("qtyRuleValue", mEdtQty.getText().toString().trim());
                httpPost(ContractConstant.SAVEORUPDATEPBRSITEMTEMPRULE, map, 0, true, "");
            }

        } else if (i == R.id.price_type_fixed) {
            priceRuleType = "0";

            setPriceHint();
            if (TextUtils.isEmpty(mPriceGuding)) {
                mEdtePrice.setText("");
                mEdtePrice.setHint("输入固定的发布价格（单位：元）");
                mTilPrice.updateHint();
            } else {
                mEdtePrice.setText(mPriceGuding);
                mEdtePrice.setHint("固定的发布价格（单位：元）");
                mTilPrice.updateHint();
                mLLPrice.setVisibility(View.GONE);
            }
            mTilPrice.setVisibility(View.VISIBLE);
            mLLPrice.setVisibility(View.GONE);
            mTypeFixed.setSelected(true);
            mTypeProportion.setSelected(false);
            mLLPrice.setVisibility(View.GONE);
        } else if (i == R.id.price_type_proportion) {
            priceRuleType = "1";

            setPricePro();
            if (TextUtils.isEmpty(mPriceBili)) {
                mEdtePrice.setText("");
                mEdtePrice.setHint("输入比例 (可大于100) %");
                mTilPrice.updateHint();
            } else {
                mEdtePrice.setText(mPriceBili);
                mEdtePrice.setHint("比例 (可大于100) %");
                mTilPrice.updateHint();
            }
            mTilPrice.setVisibility(View.VISIBLE);
            mLLPrice.setVisibility(View.VISIBLE);
            mTypeFixed.setSelected(false);
            mTypeProportion.setSelected(true);

        } else if (i == R.id.qty_type_fixed) {
            qtyRuleType = "0";

            setQtyHint();
            if (TextUtils.isEmpty(mQtyGuding)) {
                mEdtQty.setText("");
                mEdtQty.setHint("输入固定的发布数量（单位：" + data.getUnit() + "）");
                mTilQty.updateHint();
            } else {
                mEdtQty.setText(mQtyGuding);
                mEdtQty.setHint("固定的发布数量（单位：" + data.getUnit() + "）");
                mTilQty.updateHint();
            }

            mTilQty.setVisibility(View.VISIBLE);
            mLLPb.setVisibility(View.GONE);
            mQtyTypeTixed.setSelected(true);
            mQtyTypeProportion.setSelected(false);

        } else if (i == R.id.qty_type_proportion) {
            qtyRuleType = "1";

            setQtyPro();
            if (TextUtils.isEmpty(mQtyBili)) {
                mEdtQty.setText("");
                mEdtQty.setHint("输入比例 (可大于100) %");
                mTilQty.updateHint();
            } else {
                mEdtQty.setText(mQtyBili);
                mEdtQty.setHint("比例 (可大于100) %");
                mTilQty.updateHint();
            }
            mTilQty.setVisibility(View.VISIBLE);
            mLLPb.setVisibility(View.VISIBLE);
            mQtyTypeTixed.setSelected(false);
            mEdtQty.setInputType(8194);
            mQtyTypeProportion.setSelected(true);

        }
    }

    private boolean hasToasthp;
    private boolean hasToasthq;

    private void setQtyHint() {
        mEdtQty.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEdtQty.setHint("固定的发布数量（单位：" + data.getUnit() + "）");
                    mTilQty.updateHint();
                } else {
                    if (TextUtils.isEmpty(mEdtQty.getText().toString())) {
                        mEdtQty.setHint("输入固定的发布数量（单位：" + data.getUnit() + "）");
                        mTilQty.updateHint();
                    } else {
                        mEdtQty.setHint("固定的发布数量（单位：" + data.getUnit() + "）");
                        mTilQty.updateHint();
                    }
                }
            }
        });
        mEdtQty.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                mEdtQty.setHint("固定的发布数量（单位：" + data.getUnit() + "）");
                mTilQty.updateHint();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if ("0".equals(qtyRuleType)) {
                    mQtyGuding = s.toString().trim();
                } else {
                    mQtyBili = s.toString().trim();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().startsWith("00") && !hasToasthp) {
                    hasToasthp = true;
                    toast("数量必须大于零");
                } else if (!s.toString().startsWith("0")) {
                    hasToasthp = false;
                    mQtyCount = s.toString().trim();
                }
            }
        });
    }

    private void setPriceHint() {
        mEdtePrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEdtePrice.setHint("固定的发布价格（单位：元）");
                    mTilPrice.updateHint();
                } else {
                    if (TextUtils.isEmpty(mEdtePrice.getText().toString())) {
                        mEdtePrice.setHint("输入固定的发布价格（单位：元）");
                        mTilPrice.updateHint();
                    } else {
                        mEdtePrice.setHint("固定的发布价格（单位：元）");
                        mTilPrice.updateHint();
                    }

                }
            }
        });

        mEdtePrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                mEdtePrice.setHint("固定的发布价格（单位：元）");
                mTilPrice.updateHint();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if ("0".equals(priceRuleType)) {
                    mPriceGuding = s.toString().trim();
                } else {
                    mPriceBili = s.toString().trim();
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                if ("0".equals(priceRuleType)) {
                    String temp = s.toString();
                    int posDot = temp.indexOf(".");
                    if (posDot <= 0) return;
                    if (temp.length() - posDot - 1 > 2) {
                        s.delete(posDot + 3, posDot + 4);
                    }
                }
                if (s.toString().startsWith("00") && !hasToasthq) {
                    hasToasthq = true;
                    toast("价格必须大于零");
                } else if (!s.toString().startsWith("00")) {
                    hasToasthq = false;
                    mPriceValue = s.toString().trim();
                }
            }
        });
    }


    private void setPricePro() {
        mEdtePrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEdtePrice.setHint("比例 (可大于100) %");
                    mTilPrice.updateHint();
                } else {
                    if (TextUtils.isEmpty(mEdtePrice.getText().toString())) {
                        mEdtePrice.setHint("输入比例 (可大于100) %");
                        mTilPrice.updateHint();
                    } else {
                        mEdtePrice.setHint("比例 (可大于100) %");
                        mTilPrice.updateHint();
                    }

                }
            }
        });
        mEdtePrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                mEdtePrice.setHint("比例 (可大于100) %");
                mTilPrice.updateHint();

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if ("1".equals(priceRuleType)) {
                    try {
                        if (0 != data.getPrice()) {
                            mLLPrice.setVisibility(View.VISIBLE);
                            float p = Float.parseFloat(s.toString());
                            DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                            mPricePro.setText(String.format("%s", decimalFormat.format(p * data.getPrice() / 100)));
                        } else {
                            mLLPrice.setVisibility(View.VISIBLE);
                        }

                    } catch (Exception e) {
                        mLLPrice.setVisibility(View.VISIBLE);
                        mPricePro.setText("--");
                    }
                    mPriceBili = s.toString().trim();
                } else {
                    mPriceGuding = s.toString().trim();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString().startsWith("00") && !hasToastp) {
                    hasToastp = true;
                    toast("价格必须大于零");
                } else if (!s.toString().startsWith("00")) {
                    hasToastq = false;
                    mPriceProValue = s.toString().trim();
                }
            }
        });
    }

    private boolean hasToastp;
    private boolean hasToastq;

    private void setQtyPro() {
        mEdtQty.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEdtQty.setHint("比例 (可大于100) %");
                    mTilQty.updateHint();
                } else {
                    if (TextUtils.isEmpty(mEdtQty.getText().toString())) {
                        mEdtQty.setHint("输入比例 (可大于100) %");
                        mTilQty.updateHint();
                    } else {
                        mEdtQty.setHint("比例 (可大于100) %");
                        mTilQty.updateHint();
                    }
                }
            }
        });
        mEdtQty.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                mEdtQty.setHint("比例 (可大于100) %");
                mTilQty.updateHint();

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if ("1".equals(qtyRuleType)) {
                    try {
                        if (data.getQty() != null) {
                            mLLPb.setVisibility(View.VISIBLE);
                            float pb = Float.parseFloat(s.toString());
                            mQtyPro.setText(String.format("%s", (int) (pb * Integer.parseInt(data.getQty()) / 100)));
                        } else {
                            mLLPb.setVisibility(View.VISIBLE);
                        }
                    } catch (Exception e) {
                        mLLPb.setVisibility(View.VISIBLE);
                        mQtyPro.setText("--");
                    }
                    mQtyBili = s.toString().trim();
                } else {
                    mQtyGuding = s.toString().trim();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
               /* if (s.toString().startsWith("0") && !hasToastq) {
                    hasToastq = true;
                    toast("数量必须大于零");
                } else if (!s.toString().startsWith("0")) {
                    hasToastq = false;
                    mQtyCountPro = s.toString().trim();
                }*/
            }
        });
    }
}
